package tools.batcher;
import js.Lib;
import js.w3c.html5.Core.HTMLImageElement;
import js.w3c.level3.Events.Event;
/**
 * ...
 * @author PRASS
 */

class Batcher 
{
	public var killed		: Bool;
	
	private var _fCallBack 	: Dynamic;
	private var _target		: Dynamic;
	private var _urls 		: Array<String>;
	private var _img		: HTMLImageElement;
	
	public function new( target : Dynamic, fCallBack : Dynamic ) 
	{
		_fCallBack = fCallBack;
		_target = target;
		_urls = new Array<String>();
	}
	
	public function addItem( url : String ) : Void
	{
		_urls.push(url);
	}
	
	public function start() : Void
	{
		_load();
	}
	
	private function _load() : Void
	{
		_img = untyped js.Lib.document.createElement("IMG");
		_img.onload = _loaded;
		_img.src = _urls[ _urls.length - 1 ];
	}
	
	private function _loaded(e:Event) : Void
	{
		_urls.pop();
		
		if (_urls.length > 0 )
			_load();
		else if(!killed)
			Reflect.callMethod( _target, _fCallBack, []);
			
	}
	
}